package com.mojo.concurrent.threadsafe;

import java.util.stream.IntStream;

/**
 * 线程安全问题实现
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class ThreadSafe {
    public static void main(String[] args) {
        //RunnableImpl runnable = new RunnableImpl();
        //Thread thread1 = new Thread(runnable);
        //Thread thread2 = new Thread(runnable);
        //Thread thread3 = new Thread(runnable);
        //thread2.start();
        //thread1.start();
        //thread3.start();
        long s = System.currentTimeMillis();
        SyncCounter syncCounter = new SyncCounter();
        IntStream.range(0, 1000000).parallel().forEach(i -> syncCounter.count());
        System.out.println(syncCounter.getNum());
        long e = System.currentTimeMillis();
        System.out.println(e - s);
    }

    static class SyncCounter {
        int num = 0;

        public int count() {
            synchronized (this) {
                return num++;
            }
        }


        synchronized public int incre() {
            return num++;
        }

        public int getNum() {
            return num;
        }
    }
}
